//
//  NSString+FileHandle.m
//  CodeGenerator
//
//  Created by 丁玉松 on 2017/9/15.
//  Copyright © 2017年 Beijing Yingyan Internet Co., Ltd. All rights reserved.
//

#import "NSString+FileHandle.h"

@implementation NSString (FileHandle)



-(void)yyi_writeTofilePath:(NSString *)filePath anchor:(NSString *)anchor{
    if (filePath == nil) {
        return;
    }
    //待写入数据
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];

    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSLog(@"文件不存在创建");
        [[NSFileManager defaultManager] createFileAtPath:filePath contents:data attributes:nil];
        return;
    }
    
    //找到锚点
    NSString *strContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    NSRange range =  NSMakeRange(NSNotFound, 0);
    if (anchor != nil) {
        range =  [strContent rangeOfString:anchor];
    }
    
    
    //写入
    NSFileHandle* fh=[NSFileHandle fileHandleForWritingAtPath:filePath];
    
    if (range.location == NSNotFound || anchor == nil) {
        //没找到，或者没有锚点，默认追加写入
        [fh seekToEndOfFile];
        [fh writeData:data];
    }
    else
    {
        NSLog(@"range:%@",NSStringFromRange(range));
        
        //锚点之后的数据
        NSString *leadingStr = [strContent substringWithRange:NSMakeRange(0, range.location)];
        NSData *leadingData = [leadingStr dataUsingEncoding:NSUTF8StringEncoding];

        //锚点之后的数据
        NSString *tailingStr = [strContent substringWithRange:NSMakeRange(range.location, strContent.length-range.location)];
        NSData *tailingData = [tailingStr dataUsingEncoding:NSUTF8StringEncoding];
        
        //插入锚点之前
//        [fh seekToFileOffset:range.location];(这个不准确，待研究)
        [fh writeData:leadingData];
        [fh writeData:data];
        [fh writeData:tailingData];
    }
   
    [fh closeFile];
}


@end
